package com.itheima.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.advice.LogOperation;
import com.itheima.pojo.ClassQueryParam;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.PageResult;
import com.itheima.pojo.Result;
import com.itheima.service.ClassService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.List;

@RestController
@RequestMapping("/clazzs")
@Slf4j
public class ClassController {
    @Autowired
   private ClassService classService;

    @GetMapping
    Result classListInfo(ClassQueryParam classQueryParam){
        Page<Clazz> page = new Page<>(classQueryParam.getPage(),classQueryParam.getPageSize());
        LambdaQueryWrapper<Clazz> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StrUtil.isNotBlank(classQueryParam.getName()),Clazz::getName,classQueryParam.getName());
        wrapper.between(classQueryParam.getBegin()!=null&&classQueryParam.getEnd()!=null,Clazz::getEndDate,classQueryParam.getBegin(),classQueryParam.getEnd());
         page = classService.page(page, wrapper);
        List<Clazz> clazzList = page.getRecords();
        clazzList.forEach((clazz)->{
                    if(LocalDate.now().isBefore(clazz.getBeginDate())  ){
              clazz.setStatus("未开班");
          }else if( LocalDate.now().isAfter(clazz.getEndDate())  ){
              clazz.setStatus("已结课");
          }else {
              clazz.setStatus("在读中");
          }
        });
        PageResult<Clazz> pageResult =new PageResult<>(page.getTotal(),page.getRecords());
        return Result.success(pageResult);
    }
    // like contans('%', #{name} ,'%')
    @GetMapping("/list")
    Result findAll(){
        List<Clazz> clazzeList =classService.list();
        return Result.success(clazzeList);
    }
    @PostMapping
    @LogOperation
    Result save(@RequestBody Clazz clazz){
        log.info("执行了保存方法");
        classService.save(clazz);
        return Result.success();
    }
    @GetMapping("/{id}")
    Result getById(@PathVariable Integer id){
        Clazz clazz = classService.getById(id);
        return Result.success(clazz);
    }
    @DeleteMapping("/{id}")
    @LogOperation
    Result delById(@PathVariable Integer id){
        classService.removeById(id);
        return Result.success();
    }

    @PutMapping
    @LogOperation
    Result updateClazz(@RequestBody Clazz clazz){
        classService.updateById(clazz);
        return Result.success();
    }




}
